package com.recharge.common.util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * <h1>AES加密</h1>
 * <p>只实现了ECB模式128位加密和解密</p>
 *
 * @author kui
 */
public class AESUtil {

    /**
     * AES加密
     *
     * @param data   加密数据
     * @param keyStr 加密key
     * @return java.lang.String
     */
    public static String encrypt(String data, String keyStr) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKeySpec key = new SecretKeySpec(keyStr.getBytes("UTF-8"), "AES");
            cipher.init(1, key);
            return Base64.encodeBase64String(cipher.doFinal(data.getBytes("UTF-8")));
        } catch (Exception e) {
            System.out.println("AES加密失败\ninfo:" + e.getMessage());
        }
        return "";
    }

    /**
     * AES解密
     *
     * @param base64Data 解密内容
     * @param keyStr     解密Key
     * @return java.lang.String
     */
    public static String decrypt(String base64Data, String keyStr) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKeySpec key = new SecretKeySpec(keyStr.getBytes("UTF-8"), "AES");
            cipher.init(2, key);
            return new String(cipher.doFinal(Base64.decodeBase64(base64Data)));
        } catch (Exception e) {
            System.out.println("AES解密失败\ninfo: " + e.getMessage());
        }
        return "";
    }

    public static void main(String[] args) throws Exception {
        String encrypt = encrypt("asbewrbetb", "1234567891234567");
        System.out.println("encrypt: " + encrypt);
        String decrypt = decrypt(encrypt, "1234567891234566");
        System.out.println("decrypt: " + decrypt);
    }

}
